package com.richie696.bank.config;

import com.alibaba.druid.pool.DruidDataSource;
import mybatis.plugins.SqlSessionFactoryBean;
import mybatis.session.SqlSessionFactory;
import spring.annotations.*;
import spring.transaction.DataSourceTransactionManager;
import spring.transaction.PlatformTransactionManager;
import spring.transaction.TransactionManager;

import javax.sql.DataSource;

@EnableWebMvc()
@MapperScan({
        "com.richie696.**.dao",
        "com.richie696.**.service.impl",
        "com.richie696.**.controller"
})
@PropertySource({"classpath:jdbc.properties"})
@EnableTransactionManagement
public class ApplicationConfig {

    @Value("#{jdbc.driverClassName}")
    private String driverClassName;

    @Value("#{jdbc.url}")
    private String url;

    @Value("#{jdbc.username}")
    private String username;

    @Value("#{jdbc.password}")
    private String password;

    @Value("#{mybatis.mapperLocation}")
    private String mapperLocation;

    @Value("#{mybatis.configLocation}")
    private String configLocation;

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDefaultAutoCommit(false);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setConfigLocation(configLocation);
        factoryBean.setMapperLocation(mapperLocation);
        return factoryBean.getObject();
    }


    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        PlatformTransactionManager ptm = new DataSourceTransactionManager();
        ptm.setDataSource(dataSource);
        return ptm;
    }
}
